<template>
    <div class="register">
        <el-card class="box-card" style="max-width: 480px">
            <template #header>
                <div class="card-header">
                </div>
            </template>
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="registerForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="姓名：" prop="userName">
                    <el-input v-model="registerForm.userName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="性别：" prop="sex">
                    <el-select v-model="registerForm.sex" placeholder="请选择性别">
                        <el-option label="男" value="2"></el-option>
                        <el-option label="女" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="年龄：" prop="age">
                    <el-input v-model="registerForm.age" placeholder="请输入年龄" />
                </el-form-item>
                <el-form-item v-if="registerForm.roleId == '1'" label="学号：" prop="account">
                    <el-input v-model="registerForm.account" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item v-if="registerForm.roleId != '1'" label="工号：" prop="account">
                    <el-input v-model="registerForm.account" placeholder="请输入工号" />
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input v-model="registerForm.password" type="password" show-password placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="确认密码：">
                    <el-input v-model="rePassword" type="password" show-password placeholder="请再次输入密码" />
                </el-form-item>
                <el-form-item label="工作单位：" prop="job">
                    <el-select v-model="registerForm.job" filterable remote :remote-method="universityFindAll()"
                        placeholder="请输入工作单位">
                        <el-option v-for="item in universityArr" :key="item.id" :label="item.competentDepartment"
                            :value="item.id">
                            <span style="float: left">{{ item.competentDepartment }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="form-item" label="验证码：" prop="code">
                    <el-input class="input" v-model="registerForm.code" placeholder="请输入验证码" />
                    <canvas ref="verify" @click="handleDraw" :width="state.width" :height="state.height"></canvas>
                </el-form-item>
                <el-form-item>
                    <el-button class="lookButton" type="primary" @click="register(registerForm)">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="return">
                    <div>
                        <el-button type="info" round @click="reset()">重置</el-button>
                    </div>
                    <div class="returnLink">
                        <el-link @click="$router.push('/login')">已有帐号？返回登录</el-link>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElNotification } from 'element-plus';
import { addUser } from '../../api/user';
import { getByNameUn } from '../../api/university'
import { draw } from '../../utils/verificationCode.ts';

// 1 引入useRouter路由信息方法
import { useRoute, useRouter } from 'vue-router'
// 2 获取实例
const route = useRoute()

const { roleId } = route.query

// 页面跳转
const router = useRouter()

const verify = ref(null)
const state = reactive({
    pool: 'abcdefghijkmnpqrstuvwxyz0123456789',
    // 声明两个变量存验证码的宽高
    width: 140,
    height: 30,
    // 验证码最终存储的位置
    imgCode: ''
})
// 初始化绘制图像验证码
onMounted(() => {
    state.imgCode = draw(verify, state)
    console.log(state.imgCode);
    registerForm.value.roleId = Array.isArray(roleId) ? (roleId[0] || '') : String(roleId)
    console.log(registerForm.value.roleId);
})
// 点击之后重新绘制图形验证码
const handleDraw = () => {
    state.imgCode = draw(verify, state)
    console.log(state.imgCode);
}

interface RuleForm {
    userName: string;
    sex: string;
    age: number;
    account: string;
    password: string;
    code: string;
    job: string;
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    userName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    sex: [
        { required: true, message: '请输入性别', trigger: 'blur' }
    ],
    age: [
        { required: true, message: '请输入年龄', trigger: 'blur' }
    ],
    job: [
        { required: true, message: '请输入工作单位', trigger: 'blur' }
    ],
    account: [
        { required: true, message: '账号或密码不能为空', trigger: 'blur' },
        // { min: 3, max: 6, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '账号或密码不能为空', trigger: 'blur' },
        // { min: 3, max: 6, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
})
// 注册信息
const registerForm = ref({
    userName: '',
    sex: '',
    age: 0,
    account: '',
    password: '',
    code: '',
    job: '',
    roleId: ''
})
const rePassword = ref('')
// 学校信息
const universityArr = ref([] as any[]);
const universityFindAll = () => {
    getByNameUn({ name: registerForm.value.job }).then((res: any) => {
        if (res.code == 2000) {
            universityArr.value = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
// 注册按钮
const register = async (registerForm: any) => {
    ruleFormRef.value?.validate((valid: any) => {
        if (valid) {
            if (registerForm.password != rePassword.value) {
                console.log(rePassword.value);
                ElMessage.error('两次密码不一致')
            }
            if (registerForm.code == state.imgCode) {
                console.log(registerForm);
                addUser({ ...registerForm }).then((res: any) => {
                    if (res.code === 2000) {
                        console.log(res.message);
                        ElNotification({
                            title: '成功',
                            message: '注册成功',
                            type: 'success',
                        })
                        reset()
                        router.push('/')
                    } else {
                        ElMessage.error(res.message)
                    }
                })
            } else {
                ElMessage.error('验证码输入错误')
                registerForm.value.code = ''
            }
        } else {
            ElMessage.error("表单验证失败")
        }
    })
}
const reset = () => {
    registerForm.value = {
        userName: '',
        sex: '',
        age: 0,
        account: '',
        password: '',
        code: '',
        job: '',
        roleId: ''
    }
}
</script>

<style scoped lang="scss">
.register {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: url("../../assets/image/login.png");
    background-size: 100% 100%;
}

.el-card {
    width: 500px;
    // opacity: 0.8;
    position: absolute;
    top: 200px;
    left: 170px;
}

/* ::v-deep是vue3提供的深度选择器，.el-form-item__label是element-plus官方定义的类 */
::v-deep .el-form-item__label {
    font-size: 22px;
    font-weight: 900;
    font-family: '华文新魏';
}


.form-item {
    display: flex;
    justify-content: center;
    align-items: center;
}

.return {
    display: flex;
}
.returnLink {
    padding: 0 0 0 250px;
}

.input {
    width: 160px;
    padding-right: 10px;
}

.lookButton {
    width: 440px;
    background-color: #9bbde8;
    color: #fff;
    border: 1px solid #9bbde8;
}

.lookButton:hover {
    width: 440px;
    background-color: #fff;
    color: #50bbff;
    border: 1px solid #50bbff;
}

.lookButton:active {
    width: 440px;
    background-color: #fff;
    color: #50bbff;
    border: 1px solid #50bbff;
}
</style>